#include "xml_interface.h"
#include "xml.h"


BOOL xml_get_root_node(const uin8_t *file_name, xml_node_t *pnode)
{
    xmlctx*     xctx;
    xmldocnode* doc;
    xmlnode*    nodep;
    xmlerr      ecode;

    if (!(xctx = XmlCreate(&ecode, (oratext *) file_name, NULL)))
    {
	printf( "Failed to create XML context, error %u\n", (unsigned) ecode);
	return FALSE;
    }

    if (!(doc = XmlLoadDom(xctx, &ecode, "file", DOCUMENT, "validate", TRUE,
			   "discard_whitespace", TRUE, NULL)))
    {
	printf( "Parse failed, error %u\n", (unsigned) ecode);
	return FALSE;
    }

    nodep = XmlDomGetDocElem( xctx, doc);
    pnode->xml_node = nodep;
    pnode->xml_instance = xctx;
    pnode->xml_doc_instance = doc;
    return TRUE;
}


BOOL xml_get_first_child(const xml_node_t *parent_node, xml_node_t *child_node)
{
	child_node->xml_instance = parent_node->xml_instance;
	child_node->xml_doc_instance = parent_node->xml_doc_instance;
	child_node->xml_node = XmlDomGetFirstChild(parent_node->xml_instance, parent_node->xml_node);
	return (child_node->xml_node) ? TRUE : FALSE;
}

BOOL xml_get_next_sibling(const xml_node_t *base_node, xml_node_t *sibling)
{
	*sibling = *base_node;
	sibling->xml_node = XmlDomGetNextSibling(base_node->xml_instance, base_node->xml_node);
	return (sibling->xml_node) ? TRUE : FALSE;
}

void xml_get_node_name(const xml_node_t *pnode, uint8_t *buffer, uint16_t max_len)
{
	uint8_t *name = XmlDomGetNodeName(pnode->xml_instance, pnode->xml_node);
	if (strlen(name) > max_len) {
		printf("Warning: Insufficient buffer length while fetching node name: %s\n", name);
		strncpy(buffer, name, max_len);
	} else {
		strcpy(buffer, name);
	}
	return;
}

}
	
void xml_get_text_node_name(const xml_node_t *pnode, uint8_t *buffer, uint16_t max_len)
{
	xml_node_t child_node;
	uint8_t *name;

	if (xml_get_first_child(pnode, &child_node)) {
		name = XmlDomGetNodeValue(pnode->xml_instance, child_node->xml_node);
		if (strlen(name) > max_len) {
			printf("Warning: Insufficient buffer length while fetching text node name: %s\n", name);
			strncpy(buffer, name, max_len);
		} else {
			strcpy(buffer, name);
		}
	} else {
		buffer[0] = 0;	// empty string
	}
}

void xml_get_node_attribute(const xml_node_t *pnode, const uint8_t *attr_name, uint8_t *attr_val_buf, uint8_t max_val_len, \
				const uint8_t *default_attribute_val)
{
	uin8_t *attr_value = XmlDomGetAttr(pnode->xml_instance, pnode->xml_node, (oratext *)attr_name);
	if (attr_value) {
		if (stren(attr_value) > max_val_len) {
			printf("Warning: Insuficient buffer length for fetching attribute value %s\n", attr_value);
			strncpy(attr_val_buf, attr_value, max_val_len);
		} else {
			strcpy(attr_val_buf, attr_value);
		}
	} else {
		strcpy(attr_val_buff, default_attribute_val);
	}

	return;
}
